import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import modules from './modules'
import storage from '@/utils/storage'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: modules,
  state: {
    userInfo: {},
    loadding: 0,
    currBtn: '',
    startLoad: false,
    isLogin: false,
    menuTree: [],
    currentMenu: [], // 控制当前选中的菜单项
    permCodes: {},
    isCollapsed: false,
    dialogFlag: false,
    role: storage.session.get('role'),
    theme: 'light',
    openMenu: [] // 展开菜单项
  },
  // 状态修改方法
  // 使用store.commit()来调用
  mutations: {
    // 存放同步读取、修改state的的方法
    showloadding (state, load) {
      load ? ++state.loadding : --state.loadding
    },
    clearloading (state) {
      state.loadding = 0
    },
    startLoading (state, load) {
      state.startLoad = load
    },
    setIsLogin (state, val) {
      state.isLogin = val
    },
    setUserInfo (state, user) {
      state.userInfo = user // Object.assign(state.userInfo, user);
    },
    setOpenMenu(state, menuKey) {
      state.openMenu = menuKey
    },
    setUserPerm (state, data) {
      if (!Array.isArray(data)) {
        return
      }
      let permCodes = {}
      state.permCodes = mapPermCodes(data)
      console.log('permCodes',state.permCodes)
    },
    setCollapsed (state, isCollapsed) {
      state.isCollapsed = isCollapsed
    },
    setRole (state, role) {
      state.role = role
    },
    setCurrentMenu (state, menuKey) {
      state.currentMenu = [menuKey]
      console.log('state.currentMenu',state.currentMenu)
    },
    setDialogFlag (state, payload) {
      state.dialogFlag = payload
    },
    setCurrBtn (state, payload) {
      state.currBtn = payload
    }
  },
  // 可以用store.dispatch来调用
  actions: {
    // 存放异步读取、修改state的的方法
    setLoading (context, load) {
      context.commit('setIsLoading', load)
    },
    cancelLoading (context) {
      context.commit('resetLoadCnt')
    }
  },
  getters
})

function mapPermCodes(data) {
  data = data.filter(item => item.permType === '2')
  const permCodes = {}
  for (let i = 0; i < data.length; i++) {
    const temp = data[i]
    const permCode = temp.permCode.trim()
    if (permCode)
      permCodes[permCode] = 1
  }
  return permCodes
}

// 菜单权限控制
const menuPerms = ['/baseSetting/enterprise']

// this.$store.state.name  使用store仓库中的变量

// 修改或存储state中的变量
// this.$store.commit('在mutations中的方法名称',参数)<br>//将参数传给store下面的方法中，修改变量名
// this.$store.commit("setToken",result.data.token)
